package org.ytor.common.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.ytor.common.exception.BaseException;

import java.util.Map;

/**
 * created by yangtong on 2025/4/13 21:05:49
 * <br/>
 * 维护一个全局唯一的Gson对象，并将json操作封装成静态方法
 */
public class Jsons {
    private static ObjectMapper objectMapper;

    public static final TypeReference<Map<String, String>> MAP_OF_STRING_STRING = new TypeReference<>() {
    };
    public static final TypeReference<Map<String, Object>> MAP_OF_STRING_OBJECT = new TypeReference<>() {
    };

    /**
     * 注册jackson
     */
    public static void register(ObjectMapper objectMapper) {
        Jsons.objectMapper = objectMapper;
    }

    public static <T> T fromJsonStr(String jsonStr, Class<T> type) {
        try {
            return objectMapper.readValue(jsonStr, type);
        } catch (JsonProcessingException e) {
            throw new BaseException(e);
        }
    }

    public static <T> T fromJsonStr(String jsonStr, TypeReference<T> typeRef) {
        try {
            return objectMapper.readValue(jsonStr, typeRef);
        } catch (JsonProcessingException e) {
            throw new BaseException(e);
        }
    }

    public static <T> String toJsonStr(T obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new BaseException(e);
        }
    }

    /**
     * 对象 转 Map
     */
    public static Map<String, Object> toMap(Object obj) {
        if (obj instanceof String strObj) {
            try {
                return objectMapper.readValue(strObj, MAP_OF_STRING_OBJECT);
            } catch (JsonProcessingException e) {
                throw new BaseException(e, "json字符串转Map失败: {}", obj);
            }
        } else {
            return objectMapper.convertValue(obj, MAP_OF_STRING_OBJECT);
        }
    }

    /**
     * Map 转对象（用于反向构建）
     */
    public static <T> T fromMap(Map<String, Object> map, Class<T> clazz) {
        return objectMapper.convertValue(map, clazz);
    }

    /**
     * JSON 字符串转 Map<String, Object>
     */
    public static Map<String, Object> fromJsonStrToMap(String jsonStr) {
        return fromJsonStr(jsonStr, MAP_OF_STRING_OBJECT);
    }

    /**
     * JSON 字符串转 Map<String, String>
     */
    public static Map<String, String> fromJsonStrToStringMap(String jsonStr) {
        return fromJsonStr(jsonStr, MAP_OF_STRING_STRING);
    }
}
